﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BYUStock
{
    public  class Global
    {
        public const string StockNameList_MR = "https://api.mairui.club/hslt/list/b997d4403688d5e65a";
        public const string StockSsrqList_MR = "https://api.mairui.club/hslt/new/b997d4403688d5e65a";
        public static string StockCurrPrice_MR(string code) => $"https://api.mairui.club/hsrl/ssjy/{code}/b997d4403688d5e65a";
        public static string StockLastKDJ_MR(string code) => $"https://api.mairui.club/hszb/kdj/{code}/5m/b997d4403688d5e65a";
        public static string StockHistoryKDJ_MR(string code) => $"https://api.mairui.club/hszbl/kdj/{code}/5m/b997d4403688d5e65a";


        static WebClient Client = new WebClient();

        public  static string GetDate()
        {
            return "" + DateTime.Now.Year + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
        }

        public  static string DownloadHtmlContent(string uri, string folder = null, string name = null, string encoding = "GB2312")
        {
            byte[] bytes = null;
            try
            {
                bytes = Client.DownloadData(uri);
            }
            catch (Exception ex)
            {
                return "";
            }
            string content = Encoding.GetEncoding(encoding).GetString(bytes);
            if (folder != null && name != null)
            {
                var localPath = AppDomain.CurrentDomain.BaseDirectory + $@"{folder}\";
                if (!Directory.Exists(localPath))
                {
                    try
                    {
                        Directory.CreateDirectory(localPath);
                    }
                    catch { }
                }
                File.WriteAllBytes($@"{localPath}{name}.html", bytes);
            }
            Console.WriteLine(content);
            return content;
        }

        const string UriBkHome_SOHU = "https://q.stock.sohu.com/cn/bk.shtml";
        static Dictionary<string, string> Bks = new Dictionary<string, string>();
        public  static (int, int) RefreshBkList()
        {
            var localPath = AppDomain.CurrentDomain.BaseDirectory + $@"BK\";
            var date = "" + DateTime.Now.Year + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
            //WBrower_BK.Url = new Uri(UriBkHome);
            byte[] bytes = Client.DownloadData(UriBkHome_SOHU);
            if (!Directory.Exists(localPath))
            {
                try
                {
                    Directory.CreateDirectory(localPath);
                }
                catch { }
            }
            File.WriteAllBytes($@"{localPath}{date}.html", bytes);
            string content = Encoding.GetEncoding("GB2312").GetString(bytes);
            Console.WriteLine(content);
            var matchs = Regex.Matches(content, @"bk_\d\d\d\d\D*<");
            var connStr = "Data Source =" + AppDomain.CurrentDomain.BaseDirectory + "stock_base.db;";
            using (var conn = new SQLiteConnection(connStr))
            {
                conn.Open();
                using (var cmd = new SQLiteCommand())
                {
                    cmd.Connection = conn;
                    int updateFails = 0;
                    int updateSuccs = 0;
                    foreach (Match match in matchs)
                    {
                        var subs = match.Value.Split('.');
                        var bkCode = subs[0];
                        var bkName = subs[1].Substring(23).Split('<')[0];
                        if (!Bks.ContainsKey(bkCode))
                        {
                            Bks.Add(bkCode, bkName);
                            var sql1 = $@"select ID from GroupKind where ID = '{bkCode}';";
                            cmd.CommandText = sql1;
                            var exsit = cmd.ExecuteScalar();
                            if (exsit == null)
                            {
                                var sql = $@"insert into GroupKind values('{bkCode}','{bkName}','BYU',0,{date});";
                                cmd.CommandText = sql;
                                var result = cmd.ExecuteNonQuery();
                                if (result != 1)
                                {
                                    updateFails++;
                                }
                                else
                                {
                                    updateSuccs++;
                                }
                            }
                        }
                    }
                    return (updateSuccs, updateFails);
                }
            }
        }


        public  static (float, float) QueryStockRealtimeQuotes_THS(string stockCode)
        {
            var uri_THS = $@"https://stockpage.10jqka.com.cn/realHead_v2.html#hs_{stockCode}";
            var content = DownloadHtmlContent(uri_THS, encoding: "UTF-8");
            {
                return (0, 0);
            }
        }
    }
}
